package shared.file

import java.io.File

class Filesystem {

  private var folders: List[SharedFolder] = Nil
  
  def addFolder (folder: File) = add(new SharedFolder(folder))
  
  protected def add(folder: SharedFolder) = synchronized{ folders = folder :: folders}
  
  def allFolders = folders
  
  def findLocalFile(file: String) = {
    val selected = for(folder <- folders; f <- folder.getFile(file)) yield(f)
    if(selected.isEmpty) None else Some(selected(0))
  }
  
  def queryFiles(q: shared.query.Query) = for(folder <- folders; file <- folder.findFiles(q)) yield file
  
  def allFiles = folders.toStream.flatMap{ _.allFiles.toStream }
  
  def toXML = <fs>{scala.xml.NodeSeq.fromSeq( allFolders.map(_.toXML) ) } </fs> 
  
  def getFile(file: String) = {
    val c = for( f <- allFolders; if(file.startsWith(f.root.getName))  ) yield(f)
    c.flatMap{ _.allFiles }.find( _.path == file)
  }
    
  def refresh = {
    synchronized {
      folders = folders.map { _.refresh }      
    }
  }
  
}

object Filesystem {
  
  import scala.xml._
  
  def fromXML(node: Node) = {
    val fs = new Filesystem
    node.child.map {  i => fs.add (SharedFolder.fromXML(i) )  }
    fs
  }
  
}